package com.beam.impl.bookmark;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.beam.T.Pair;
import com.beam.base.Dao;
import com.beam.base.ServiceSupport;
import com.beam.util.CollectionsUtil;
import com.beam.util.ObjectUtil;
import com.beam.util.Pager;

/**
 * 功能描述：用户书�?
 * 
 * @author beam
 */
@Service
public class BookmarkServiceImpl extends ServiceSupport<Bookmark> implements BookmarkService {

	@Autowired
	BookmarkDao bookmarkDao;
	
	public Dao<Bookmark> getDao(){
		return bookmarkDao;
	}
	
	@Override
	public List<Bookmark> find(Pager pager) {
		return bookmarkDao.find(pager,Order.asc("sort") );
	}

	@Override 
	public List<Bookmark> findByUser(Pager pager, Integer userId ){
		return bookmarkDao.find(pager, Restrictions.eq( "userId" , userId ) ,Order.asc("sort") );
	}
	@Override
	public List<Bookmark> findAllByUser(Integer userId ){
		return bookmarkDao.find( Restrictions.eq( "userId" , userId ) ,Order.asc("sort") );
	}
	
	@Override
	@Transactional
	public boolean saveOrUpdate(Bookmark bookmark){
		
		bookmark.setAddDate( new Date() );
		
		Bookmark preBookmark = preSort( bookmark );
		if( ObjectUtil.isEmpty( preBookmark ) ){
			bookmark.setSort( 1);
		}else{
			bookmark.setSort( preBookmark.getSort() + 1);
		}
		return super.saveOrUpdate( bookmark );
	}
	
	private Bookmark preSort(Bookmark bookmark) {

		List<Bookmark> bookmarkList = bookmarkDao.find(Pager
				.getMinPager(), Restrictions.eq("userId", bookmark.getUserId() ) , Order.desc("sort" ) );
		if (CollectionsUtil.isEmpty(bookmarkList))
			return null;
		else
			return bookmarkList.get(0);
	}
	
	@Override
	@Transactional
	public boolean sort(Integer id , boolean upper , Integer userId) {
		Bookmark bookmark = find( id );
		if( bookmark.getSort() == 1 ) return false;
		int nextSort = upper ? bookmark.getSort() -1 : bookmark.getSort() + 1;
		Bookmark swap = hasSame( new Pair<String,Integer>( "userId" , userId ) , new Pair<String,Integer>( "sort" , nextSort ) );
		if( ObjectUtil.isEmpty( swap ) ) return false;
		int swapSort = bookmark.getSort();
		bookmark.setSort( swap.getSort() );
		swap.setSort( swapSort );
		saveOrUpdate( bookmark );
		saveOrUpdate( swap );
		return true;
	}

	
	
}


